package org.teemor.demo.nio.channel;

import org.teemor.demo.nio.BaseTest;

import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @Description:
 * @author zhoulk
 * @date: 2020/2/21
 */
public class SocketChannelDemo implements BaseTest {

    public static void main(String[] args) throws Exception {
        baseTest();
    }


    public static void baseTest() throws Exception {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        if (!socketChannel.connect(new InetSocketAddress("127.0.0.1", 8080))) {
            System.out.println("Not connect");
            // 正真的连接
            while (!socketChannel.finishConnect()) {
                System.out.println("Not finishConnect");
            }
        }
        RandomAccessFile fromFile = new RandomAccessFile("E:\\logs\\ai-cmdc-ams.log","rw");
        FileChannel fromChannel = fromFile.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);
        while (fromChannel.read(byteBuffer)>-1) {
            byteBuffer.flip();
            while (byteBuffer.hasRemaining()) {
                socketChannel.write(byteBuffer);
            }
            byteBuffer.clear();
        }


//        socketChannel.shutdownOutput();

//        Thread.sleep(2000);
        ByteBuffer readBuffer = ByteBuffer.allocate(100);

        int bytesRead = socketChannel.read(readBuffer);
        System.out.println("bytes:" + bytesRead);
        while (bytesRead != -1) {
            byteBuffer.flip();
            String str = new String(readBuffer.array(), "UTF-8");
            System.out.println(str);
            readBuffer.clear();
            bytesRead = socketChannel.read(readBuffer);
        }

        socketChannel.close();
    }
}
